// pages/contracts/contracts.js
Page({
  data: {
    contracts: [],
    loading: true,
    currentTab: 0,
    tabs: [
      { key: 'all', name: '全部' },
      { key: 'PENDING', name: '待签署' },
      { key: 'SIGNED', name: '已签署' },
      { key: 'EXECUTING', name: '执行中' },
      { key: 'COMPLETED', name: '已完成' },
      { key: 'TERMINATED', name: '已终止' }
    ],
    page: 1,
    pageSize: 10,
    hasMore: true,
    refreshing: false
  },

  onLoad() {
    this.loadContracts();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore();
    }
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index,
      page: 1,
      contracts: [],
      hasMore: true
    });
    this.loadContracts();
  },

  // 加载合同列表
  loadContracts() {
    this.setData({ loading: true });

    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPrompt();
      return;
    }

    const currentStatus = this.data.tabs[this.data.currentTab].key;
    const params = {
      page: this.data.page,
      size: this.data.pageSize
    };

    if (currentStatus !== 'all') {
      params.status = currentStatus;
    }

    const queryString = Object.keys(params)
      .map(key => `${key}=${params[key]}`)
      .join('&');

    wx.request({
      url: `http://localhost:8080/api/user/contracts?${queryString}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const newContracts = res.data.data.content || [];
          this.setData({
            contracts: this.data.page === 1 ? newContracts : [...this.data.contracts, ...newContracts],
            hasMore: !res.data.data.last,
            loading: false,
            refreshing: false
          });
        } else {
          this.showError(res.data.message || '加载失败');
        }
      },
      fail: () => {
        // 模拟数据
        const mockContracts = this.generateMockContracts();
        const filteredContracts = this.filterContractsByStatus(mockContracts, currentStatus);
        
        this.setData({
          contracts: this.data.page === 1 ? filteredContracts : [...this.data.contracts, ...filteredContracts],
          hasMore: false,
          loading: false,
          refreshing: false
        });
      },
      complete: () => {
        wx.stopPullDownRefresh();
      }
    });
  },

  // 生成模拟合同数据
  generateMockContracts() {
    return [
      {
        id: 1,
        jobTitle: '前端开发工程师',
        employerName: '某科技公司',
        contractType: 'FULL_TIME',
        status: 'SIGNED',
        startDate: '2024-01-15',
        endDate: '2024-07-15',
        salary: 12000,
        salaryType: 'MONTHLY',
        signTime: '2024-01-10 14:30:00',
        createTime: '2024-01-08 10:00:00'
      },
      {
        id: 2,
        jobTitle: 'UI设计师',
        employerName: '创意设计工作室',
        contractType: 'PART_TIME',
        status: 'EXECUTING',
        startDate: '2024-01-20',
        endDate: '2024-03-20',
        salary: 200,
        salaryType: 'DAILY',
        signTime: '2024-01-18 16:20:00',
        createTime: '2024-01-15 09:30:00'
      },
      {
        id: 3,
        jobTitle: '数据分析师',
        employerName: '数据科技有限公司',
        contractType: 'TEMPORARY',
        status: 'PENDING',
        startDate: '2024-02-01',
        endDate: '2024-02-29',
        salary: 8000,
        salaryType: 'MONTHLY',
        createTime: '2024-01-25 11:15:00'
      },
      {
        id: 4,
        jobTitle: '客服专员',
        employerName: '电商平台',
        contractType: 'FULL_TIME',
        status: 'COMPLETED',
        startDate: '2023-10-01',
        endDate: '2023-12-31',
        salary: 5000,
        salaryType: 'MONTHLY',
        signTime: '2023-09-28 10:00:00',
        createTime: '2023-09-25 14:20:00'
      }
    ];
  },

  // 根据状态过滤合同
  filterContractsByStatus(contracts, status) {
    if (status === 'all') {
      return contracts;
    }
    return contracts.filter(contract => contract.status === status);
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      contracts: [],
      hasMore: true,
      refreshing: true
    });
    this.loadContracts();
  },

  // 加载更多
  loadMore() {
    this.setData({
      page: this.data.page + 1
    });
    this.loadContracts();
  },

  // 查看合同详情
  viewContract(e) {
    const contractId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/contract-detail/contract-detail?id=${contractId}`
    });
  },

  // 签署合同
  signContract(e) {
    e.stopPropagation();
    const contractId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认签署',
      content: '确定要签署此合同吗？签署后将不可撤销。',
      success: (res) => {
        if (res.confirm) {
          this.performSignContract(contractId);
        }
      }
    });
  },

  // 执行签署合同
  performSignContract(contractId) {
    const token = wx.getStorageSync('token');

    wx.showLoading({
      title: '签署中...'
    });

    wx.request({
      url: `http://localhost:8080/api/user/contracts/${contractId}/sign`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '签署成功',
            icon: 'success'
          });
          this.refreshData();
        } else {
          wx.showToast({
            title: res.data.message || '签署失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '签署成功',
          icon: 'success'
        });
        // 更新本地数据
        this.updateContractStatus(contractId, 'SIGNED');
      }
    });
  },

  // 更新合同状态
  updateContractStatus(contractId, newStatus) {
    const contracts = this.data.contracts.map(contract => {
      if (contract.id === contractId) {
        return {
          ...contract,
          status: newStatus,
          signTime: new Date().toLocaleString()
        };
      }
      return contract;
    });
    
    this.setData({ contracts });
  },

  // 下载合同
  downloadContract(e) {
    e.stopPropagation();
    const contractId = e.currentTarget.dataset.id;
    
    wx.showLoading({
      title: '下载中...'
    });

    // 模拟下载
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '下载成功',
        icon: 'success'
      });
    }, 1500);
  },

  // 显示登录提示
  showLoginPrompt() {
    wx.showModal({
      title: '未登录',
      content: '请先登录后查看合同信息',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          });
        }
      }
    });
  },

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none'
    });
    this.setData({
      loading: false,
      refreshing: false
    });
  },

  // 格式化合同类型
  formatContractType(type) {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  },

  // 格式化合同状态
  formatContractStatus(status) {
    const statusMap = {
      'PENDING': '待签署',
      'SIGNED': '已签署',
      'EXECUTING': '执行中',
      'COMPLETED': '已完成',
      'TERMINATED': '已终止'
    };
    return statusMap[status] || status;
  },

  // 格式化薪资
  formatSalary(salary, salaryType) {
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    return `${salary}元${unit}`;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'PENDING': '#fa8c16',
      'SIGNED': '#1890ff',
      'EXECUTING': '#52c41a',
      'COMPLETED': '#722ed1',
      'TERMINATED': '#f5222d'
    };
    return colorMap[status] || '#666';
  }
});
